/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action;

import com.opensymphony.xwork2.ActionContext;
import dao.UserDAO;
import dto_pakinfo.User;
import util.StringUtil;
import java.util.Map;
import util.ServerValidation;

/**
 *
 * @author duonghung1369
 */
public class LoginController extends BaseController {

    private String username;
    private String password;
    private UserDAO userDAO;

    public LoginController() {
        userDAO = new UserDAO(User.class);
    }

    public String login() {
        userDAO.openSession();
        User result = userDAO.checkLogin(getUsername(), getPassword());
        userDAO.closeSession();
        if (result != null && !result.isIsDeleted()) {
            Map session = ActionContext.getContext().getSession();
            session.put(StringUtil.LOGINED, Boolean.TRUE);
            session.put(StringUtil.USERNAME, username);
            session.put(StringUtil.USERID, result.getId());
            session.put(StringUtil.ISADMIN, (Boolean) result.isIsAdmin());
            return SUCCESS;
        } else {
            addActionError("Invaid username or password. Try again!");
            return INPUT;
        }
    }

    public String logout() {
        Map session = ActionContext.getContext().getSession();
//        session.remove(StringUtil.LOGINED);
//        session.remove(StringUtil.USERNAME);
//        session.remove(StringUtil.USERID);
        session.clear();
        return SUCCESS;
    }

    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }

    /**
     * @param username the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    public String getLastURL() {
        return ServerValidation.getLastURL();
    }
}
